import {useAuthStore} from "../store/token.js"

const BASE_URL = 'http://47.99.64.234:8004/app/'; // 基础URL
// const BASE_URL = 'api/app/';

export function request(config = {}) {
    let {
        url,
        data = {},
        method = 'GET',
        header = {},
        timeout
    } = config;

    // 拼接完整的URL
    url = BASE_URL + url;
	
	// 获取 Pinia store
	const authStore = useAuthStore();

    // 默认添加token和refreshToken到请求头
    header = {
		...header,
      'access-token': authStore.getToken || ''
    };
	
    return new Promise((resolve, reject) => {
        uni.request({
            url,
            data,
            method,
            header,
            timeout: 300000,
            success: (res) => {
                const { code, data: resData, message } = res.data;
                if (code === 200) {
                    resolve(res.data.data);
				}
				else if(code === 601 || code === 602 ){
					uni.navigateTo({
						url:"/pages/login/login"
					})
				}
                else {
                    // 其他错误
                    uni.showToast({
                        title: message || '请求失败',
                        icon: 'none'
                    });
                    reject(res.data.data);
                }
            },
            fail: (err) => {
                uni.showToast({
                    title: '网络请求失败，请检查网络',
                    icon: 'none'
                });
                reject(err);
            }
        });
    });
}
